package com.szholly.pro.watergas_server.ps.schedule;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;
import com.szholly.pro.watergas_server.common.data.DataUtil;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import lrq.common.MyLog;

public class TaskGenerate implements Job {
	protected static Logger logger = null;

	/**
	 * 生成任务单
	 * gislin
	 * 2015年10月16日
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	public void Generate() throws Exception {
		
		if(logger == null){
			logger = MyLog.getLogger("taskGenerate");
		}
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String dateStr = sf.format(new Date());
		
		String sql = " SELECT otc.*,ms.name station_name,oj.job_name,sg.OPERATION_GROUP_ID,ot.FINISH_TIME,otc.EFFECTIVE_TIME from OC_TASK_CONFIG otc \n "
				+ " left join BC_SITE_INFO ms ON ms.code = otc.station_id\n"
				+ " LEFT JOIN operation_job oj ON oj.guid = otc.job_id\n"
				+ "	LEFT JOIN OPERATION_TASK ot ON otc.CURRENT_TASK_CODE = ot.TASK_CODE \n "
				+ " INNER JOIN OPERATION_GROUP_STATION_ASSO sg ON sg.STATION_ID = otc.STATION_ID \n "
				+ "	where (otc.CURRENT_TASK_CODE is null or ot.TASK_STATUS = '1') and sg.OPERATION_GROUP_ID is not null ";
		List<RowBase> list = DataUtil.getSelectRows(sql, null);
		List<RowBase> resultList = new ArrayList<>();
		
		//两类情况可以生成新任务，一类是计划还没有对应任务的，一类是已完成，并且已经到了新任务开始的时间了
		for(int i=0;i<list.size();i++){
			
			RowBase row = list.get(i);
			
			if(row.get("CURRENT_TASK_CODE") == null){
				resultList.add(row);
				continue;
			}
			
			String timeCycle = row.get("TASK_CYCLE")+"";
			Date finishTime = (Date)row.getValue(GlobalDataType.DateTime,"FINISH_TIME");
			Date effectiveTime = (Date)row.getValue(GlobalDataType.DateTime,"EFFECTIVE_TIME");
			
			//如果还没到生效时间，则不生成任务
			if(effectiveTime != null && Calendar.getInstance().getTime().getTime() < effectiveTime.getTime()){
				continue;
			}
			
			if(finishTime == null){
				continue;
			}
			
			Calendar deathCal = Calendar.getInstance();
			Calendar currentCal = Calendar.getInstance();
			deathCal.setTime(finishTime);
			int timeCycleNum = Integer.parseInt(timeCycle.replaceAll("[a-zA-Z]",""));
			
			if(timeCycle.indexOf("D")>0){
				deathCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
			}
			else if(timeCycle.indexOf("M")>0){
				deathCal.add(Calendar.MONTH, timeCycleNum);
			}
			
			if(deathCal.before(currentCal)){
				resultList.add(row);
			}
		}
		
		try {
			
			for(int i=0;i<resultList.size();i++){
				RowBase row = resultList.get(i);
				String taskSchedulerId = row.getSafeString("OPERATIONS_TASK_SCHEDULER_id");
				String timeCycle = row.get("TASK_CYCLE")+"";
				String stationId = row.get("STATION_ID")+"";
				String parmId = row.get("PARM_ID")+"";
				String groupId = row.get("OPERATION_GROUP_ID")+"";
				String jobId = row.get("JOB_ID")+"";
				String stationName = row.getSafeString("STATION_NAME");
				String jobName = row.getSafeString("job_name");
				String configGUID = row.getSafeString("GUID");
				
				Object checkExists = DataUtil.getScale(" SELECT COUNT(*) FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
				
				if((checkExists+"").equals("0")){
					DataUtil.ExecuteUpdateSql("INSERT INTO OP_SITE_TASK_COUNT(STATION_ID,TASK_COUNT,UPDATE_TIME) VALUES('"+stationId+"',1,sysdate)", null);
				}
				else{
					DataUtil.ExecuteUpdateSql(" UPDATE OP_SITE_TASK_COUNT SET TASK_COUNT = TASK_COUNT+1,UPDATE_TIME = sysdate WHERE STATION_ID = '"+stationId+"' ", null);
				}
				
				Object taskCountStr = DataUtil.getScale(" SELECT TASK_COUNT FROM OP_SITE_TASK_COUNT WHERE STATION_ID = '"+stationId+"' ", null);
				
				int taskCount = 0;
				if(taskCountStr != null){
					taskCount = Integer.parseInt(taskCountStr+"");
				}
				
				int timeCycleNum = Integer.parseInt(timeCycle.replaceAll("[a-zA-Z]",""));
				Calendar endCal = Calendar.getInstance();
				if(timeCycle.indexOf("D")>0){
					endCal.add(Calendar.DAY_OF_MONTH, timeCycleNum);
				}
				else if(timeCycle.indexOf("M")>0){
					endCal.add(Calendar.MONTH, timeCycleNum);
				}
				else if(timeCycle.indexOf("H")>0){
					endCal.add(Calendar.HOUR_OF_DAY, timeCycleNum);
				}
				else if(timeCycle.indexOf("W")>0){
					endCal.add(Calendar.WEEK_OF_MONTH, timeCycleNum);
				}
				
				String taskCode = dateStr + "-" + stationId + "-" +taskCount;
				
				String insertSql = " insert into operation_task (GUID,OPERATIONS_TASK_SCHEDULER_id, STATION_ID, PARM_ID, OPERATION_GROUP_ID, TASK_STATUS, START_TIME, END_TIME, FINISH_TIME, FINISH_BY, CREATE_TIME, TASK_CODE, JOB_ID, IS_UNUSUAL) "
						+ "values (sys_guid(),@taskSchedulerId, @stationId, @parmId,@groupId, '0', sysdate, @endTime, null, '', sysdate, @taskCode,@jobId, '')";
				
				List<GlobalParameter> parms = new ArrayList<>();
				parms.add(new GlobalParameter("stationId", stationId));
				parms.add(new GlobalParameter("parmId", parmId));
				parms.add(new GlobalParameter("groupId", groupId));
				parms.add(new GlobalParameter("endTime", new java.sql.Date(endCal.getTime().getTime())));
				parms.add(new GlobalParameter("taskCode", taskCode));
				parms.add(new GlobalParameter("jobId", jobId));
				parms.add(new GlobalParameter("taskSchedulerId", taskSchedulerId));
				DataUtil.ExecuteUpdateSql(insertSql, parms);
				
				String updateOTCCodeSql = " UPDATE OC_TASK_CONFIG otc SET CURRENT_TASK_CODE = '"+taskCode+"' where guid = '"+configGUID+"'";
				DataUtil.ExecuteUpdateSql(updateOTCCodeSql, null);
				logger.info("给"+stationId+","+stationName+"生成任务:"+jobName+",current_task_code:"+taskCode);
			}
			
		} catch (Exception e) {
			logger.error("生成任务失败",e);
		}
	}

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try {
			Generate();
		} catch (Exception e) {
			logger.error("生成任务失败",e);
		}
		
	}
	
}
